package controllers

import dao.ModeDao
import implicits.Implicits._
import org.apache.commons.io.FileUtils
import play.api.cache.AsyncCacheApi
import play.api.libs.json.Json
import play.api.mvc._
import tool.{FormTool, Tool}
import utils.Utils

import java.io.File
import java.nio.file.Files
import javax.inject.Inject
import scala.concurrent.ExecutionContext.Implicits.global
import command.CommandExec
import shared.pojo.Gene.SymbolData
import tool.Pojo.CommandData
import upickle.default._

/** Created by yz on 16/9/2021
  */
class ToolsController @Inject() (cc: ControllerComponents, cache: AsyncCacheApi)(implicit
    val modeDao: ModeDao
) extends AbstractController(cc) {

  def capsBefore = Action { implicit request =>
    Ok(views.html.tools.caps())
  }

  def caps = Action(parse.multipartFormData) { implicit request =>
    val data = FormTool.capsForm.bindFromRequest.get
    val tmpDir = Tool.createTempDirectory("tmpDir")

    val seqFile = new File(tmpDir, "data.csv")
    data.method match {
      case "Text" =>
        data.queryText.toFile(seqFile)
      case "File" =>
        val file = request.body.file("file").get
        file.ref.moveTo(seqFile, replace = true)
    }
    val refFile = new File(Tool.seqDir, s"Homo_sapiens.${data.reference}.fa")

    val execCommand = CommandExec().exec { b =>
      val command =
        s"""
           |dos2unix *
           |${Tool.binPath.unixPath}/SNP_Primer_Pipeline-1.0/run_getkasp.py ${seqFile.unixPath} ${data.ploidy} ${data.price} ${data.caps} ${data.kasp} 0 ${data.maxTm} ${data.maxSize} ${data.pickAnyway} ${refFile.unixPath}
           |""".stripMargin
      CommandData(tmpDir, command)
    }
    if (execCommand.isSuccess) {
      val alignment = new File(tmpDir, "All_alignment_raw.fa").str
      val caps = new File(tmpDir, "Potential_CAPS_primers.tsv").str
      val kasp = new File(tmpDir, "Potential_KASP_primers.tsv").str
      Tool.deleteDirectory(tmpDir)
      Ok(Json.obj("alignment" -> alignment, "caps" -> caps, "kasp" -> kasp, "valid" -> true))
    } else {
      Tool.deleteDirectory(tmpDir)
      Ok(Json.obj("valid" -> false, "message" -> execCommand.errorInfo))
    }
  }

  def searchBefore = Action { implicit request =>
    val data = Tool.transformRq.transform(reader[SymbolData])
    Ok(views.html.tools.search(data.symbol))
  }

}
